package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.query.StrategyQueryObject;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.service.IStrategyService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * 地区资源控制器
 */
@RequestMapping("/regions")
@RestController
public class RegionController {
    @Autowired
    private IRegionService regionService;
    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private ServletContext servletContext;
    @GetMapping
    public List<Region> list(Integer state) {
        return regionService.listAll(state);
    }

    /**
     * 根据地区id获取推荐攻略
     * @param queryObject
     * @return
     */
    @GetMapping(value="/{regionId}/strategies",produces = "text/html;charset=utf-8")
    public void getStrategyByRegionId(StrategyQueryObject queryObject, HttpServletResponse response) throws Exception {
        //查询某地区下的推荐攻略
        //设置攻略查询状态，不分页
        queryObject.setState(Strategy.STATE_HOT);
        queryObject.setPageSize(0);
        PageInfo hot = strategyService.query(queryObject);
        //查询某地区下的所有攻略，分页
        queryObject.setState(null);
        queryObject.setPageSize(4);
        PageInfo all = strategyService.query(queryObject);

        //通过freemarker渲染到模板后，响应回去
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
        //创建模板目录
        configuration.setDirectoryForTemplateLoading(new File(servletContext.getRealPath("template")));
        configuration.setDefaultEncoding("utf-8");
        Template template = configuration.getTemplate("strategyTemplate.ftl");
        //合成数据
        HashMap<String, Object> map = new HashMap<>();
        map.put("hot", hot);
        map.put("all", all);
        template.process(map,response.getWriter());

    }

    @GetMapping(value="/{regionId}/strategies",produces = "application/json")
    public PageInfo getStrategyList(StrategyQueryObject queryObject) throws Exception {
        queryObject.setPageSize(4);

        PageInfo pageInfo = strategyService.query(queryObject);
        return pageInfo;
    }
}
